#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import requests
from random import randint
from itertools import zip_longest
from my_app.common.query_mysql_db import query_mysql_db, now
from json.decoder import JSONDecodeError


def query_policy_content(policy_id, db_config: dict):
    """查询保单详情，返回list"""
    message = query_mysql_db(db_config, table="policy", condition=f"policy_id='{policy_id}'")
    if message:
        policy_uuid = message[0]  # 保单号的UUID
        _policy_id = message[1]  # 保单号
        try:
            policy_stand_content = json.loads(message[9])  # 保单详情
        except JSONDecodeError:
            return "JSONDecodeError"
        else:
            premium = float(message[6]) / 100 if message[6] else 'not fount'  # 保费 单位为分除以100
            amount = float(message[7]) if message[7] else 'not fount'  # 保额
            calculator = policy_stand_content['calculator']
            sku_name = 'not fount'
            if 'portfolioSkuName' in calculator:
                sku_name = calculator['portfolioSkuName']
                if sku_name == '':
                    sku_name = 'not fount'
            receive_age = "保单没有领取年龄"
            if "receiveAge" in calculator:
                receive_age = calculator['receiveAge']
                if receive_age == "":
                    receive_age = "保单有领取年龄字段，但是无值"
            risk_name, pay_period, ins_period = f"{json.dumps(policy_stand_content)}", "not fount\n条款名称、交费期间、保险期间未找到", "not fount"
            if "riskList" in calculator:
                risk_list = calculator['riskList']  # 条款
                if len(risk_list) == 1:
                    risk_name = risk_list[0]['riskName']  # 条款名称
                    pay_period = risk_list[0]['payPeriod']  # 交费期间
                    ins_period = risk_list[0]['insPeriod']  # 保险期间
                else:
                    r_n, p_p, i_p = [], [], []
                    for num, risk in enumerate(risk_list):
                        r_n.append(f"{num}<{risk['riskName']}>\n")
                        p_p.append(f"{num}<{risk['payPeriod']}>\n")
                        i_p.append(f"{num}<{risk['insPeriod']}>\n")
                    risk_name, pay_period, ins_period = "该保单有多个险种,请根据实际情况选择：\n" + "".join(r_n), "".join(p_p), "".join(i_p)
            insured_info = policy_stand_content['insuredInfo']['insuredList'][0]  # 被保人信息
            insured_gender = insured_info['insuredGender']  # 保单信息中的性别
            insured_age = insured_info['insuredAge']  # 保单信息中的年龄
            insured_age = insured_age if insured_age != '' else 'not fount'
            sex = "男" if insured_gender == "1" else "女"  # 1男  2女

            return [_policy_id, policy_uuid, premium, amount, sku_name, sex, insured_age, risk_name, pay_period, ins_period, receive_age]


def further(num):
    """四舍五入小数点后两位，返回float"""
    num = str(num)
    if "." in num:
        str_num = num.split(".")
        int_num = int(str_num[0])
        float_num1 = int(str_num[1][0])
        if float_num1 >= 5:
            int_num += 1
        return float(int_num)
    else:
        return float(num)


def json_format(_json: dict):
    """JSON格式化输出，展开形态"""
    return json.dumps(_json, ensure_ascii=False)
    # return json.dumps(_json, sort_keys=True, indent=4, separators=(', ', ': '), ensure_ascii=False)


def cash_value_run(base_cash: list, base_money: int, money: float, api_path: str, policy_uuid, policy_year, env):
    """计算现金价值
    base_cash：基础现价、base_money：每年基本金额、money：保额/保费、env：环境、policy_uuid：保单UUID
    返回tuple
    """
    header = {"x-request-lm-env": "staging"}
    body = {
        "transactionId": f"6012505915{randint(100000000, 999999999)}",
        "policyList": [{"policyUUid": policy_uuid, "endPolicyYear": policy_year}]
    }
    response = requests.post(url=api_path, json=body, verify=False, headers=header)
    print(f"{now()} - 请求接口{env}环境 - {response.request.url} - {response.status_code}")

    result_list = []  # 对比结果列表
    request_message = {}  # 每次请求的数据
    except_message = {}  # 异常列表
    http_status_message = {}  # 网络状态
    # result_list.append([1, 2, 3, 4, "成功"])

    if response.status_code != 200:
        http_status_message['httpCode'] = f"http状态 {response.status_code} 请联系开发人员！"
    else:
        http_status_message['httpCode'] = f"http状态 {response.status_code} 成功"
        policy_list = response.json()['data']['policyList']
        if policy_list:
            if policy_list[0]['status'] == '200':
                request_message['url'] = response.request.url
                request_message['payload'] = json_format(body)
                request_message['response'] = json_format(response.json())
                cash_values = policy_list[0]['cashList'][0]['cashValues']  # 返回的现价列表
                cash_years = [y['polciyYear'] for y in cash_values]  # 当前保单的所有年度
                _cash_value = [v['cashValue'] for v in cash_values]  # 当前保单所有年度的现价
                max_res_year = len(cash_years)  # 接口返回的最大年度
                max_expect_year = len(base_cash)  # 预期结果最大年度
                if max_res_year > max_expect_year or max_res_year < max_expect_year:
                    except_message['except'] = f"实际年度 {max_res_year}，预期年度 {max_expect_year} - 请检查异常"
                elif max_res_year == max_expect_year:
                    except_message['except'] = f"实际年度 {max_res_year}，预期年度 {max_expect_year}"
                for c_y, c_v, a_r in zip_longest(cash_years, _cash_value, base_cash):  # 现价信息列表数据
                    if None not in (c_y, c_v, a_r):
                        reality = int(c_v) / 100  # 实际结果除以100
                        expect = further(float(a_r * 100) * float(money) / base_money)  # 第一步四舍五入，(基础现价*100)*保额or保费 / base_money
                        expect = str(int(expect))
                        if len(expect) > 2:  # 预期结果大于2位，进入第二步四舍五入
                            expect = 0.0 if expect == '0' else further(expect[:-2] + '.' + expect[-2:])  # 第二步四舍五入，切片拼接取后两位之前和之后的，再四舍五入第一位小数
                        if reality == expect:
                            result_list.append([c_y, a_r, reality, expect, "成功"])
                        else:
                            result_list.append([c_y, a_r, reality, expect, "失败"])
                    else:
                        if not c_v and a_r:
                            result_list.append(["None", a_r, "None", further(float(a_r) * float(money) / base_money), "缺少数据"])
                        if not a_r and c_v:
                            result_list.append([c_y, "None", int(c_v) / 100, "None", "缺少数据"])
            else:
                request_message['url'] = response.request.url
                request_message['payload'] = json_format(body)
                request_message['response'] = json_format(response.json())
    return {"requestMessage": request_message, "resultList": result_list, "exceptMessage": except_message, "httpStatusMessage": http_status_message, "send_time": now()}


if __name__ == '__main__':
    print(query_policy_content(policy_id="111", db_config={}))

